package com.swdegao.iot.netty.server.qianbaotongplushandler;


import com.alibaba.fastjson.JSON;
import com.swdegao.iot.SwdegaoIotMgtServerApplication;
import com.swdegao.iot.netty.entity.ImeiInfo;
import com.swdegao.iot.netty.entity.Parameter;
import com.swdegao.iot.netty.utils.RedisUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;


public class QianBaoTongPlus_HeartBeatClientHandler extends ChannelInboundHandlerAdapter{

	@Autowired
    private RedisUtils redisUtils = SwdegaoIotMgtServerApplication.getBean(RedisUtils.class);


	@Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        ByteBuf in = (ByteBuf)evt;
        byte[] barray = new byte[in.readableBytes()];
        in.getBytes(0,barray);
        System.out.println(" 获取到数据："+ Hex.encodeHexString(barray));
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state()== IdleState.READER_IDLE){
            	//logger.info("已经120秒未收到客户端的消息了！");
            	String channelId= QianBaoTongPlus_Const.getChannelIds(ctx.channel());
            	if("".equals(channelId) || is_heartDelay(channelId)){//已经过期
                	ctx.channel().close();
            	}

            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	ctx.fireChannelRead(msg);
       // System.out.println("client says: "+msg.toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    /**
     * 验证心跳是否过期
     * @param imei
     * @return
     */
    private boolean is_heartDelay(String imei){

    	boolean flag = false;
    	try {
    		ImeiInfo imeiInfo = JSON.parseObject(redisUtils.hmGet(Parameter.imei_info,imei).toString(), ImeiInfo.class);
        	int heartbeat_delay_num = imeiInfo.getHeartbeat_delay_num();//获取心跳循环次数
    		int heartbeat_cycle = imeiInfo.getHeartbeat_cycle();
        	if(Parameter.heartbeat_cycle_check * (heartbeat_delay_num + 1) >= heartbeat_cycle*Parameter.heartbeat_delay_num) flag = true;

        	heartbeat_delay_num++;
        	imeiInfo.setHeartbeat_delay_num(heartbeat_delay_num);
        	redisUtils.hmSet(Parameter.imei_info, imei, JSON.toJSONString(imeiInfo));
    	} catch (Exception e) {
			// TODO: handle exception
			flag = true;
		}

    	return flag;
    }

}
